package online.dgyj.rgb;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.nle.mylibrary.claimer.connector.ConnectorListener;
import com.nle.mylibrary.claimer.connector.ConnectorProtocolClaimerListenerImpl;
import com.nle.mylibrary.databus.DataBus;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.device.RGBLed;
import com.nle.mylibrary.device.listener.ConnectResultListener;
import com.nle.mylibrary.util.DataTools;
import com.nle.mylibrary.util.HexUtil;


@SuppressLint("DefaultLocale")
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Handler handler;

    private String rgbIP;
    private int rgbPort;
    private int rgbAddress;
    private DataBus dataBus; // 主要为魔改方法使用,竞赛可常考其它例程写法
    private RGBLed rgbLed;  // RGB连接器


    private boolean RTULink = false;    // 是否串口连接
    private int red = 0, green = 0, blue = 0;   // RGB数值
    private int redChannelId, greenChannelId, blueChannelId;    // 红绿蓝三色通道 对应RGB控制器LED1,LED2,LED3,LED4


    ImageView lampBack; // 灯泡背景
    SeekBar redSeekBar, greenSeekBar, blueSeekBar;  // RGB
    TextView rgbValueText;  // RGB数值显示
    ImageButton switchBtn, settingBtn;  // 按钮
    private GradientDrawable gradientDrawable;  // 用于改变灯泡背景颜色

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        bind(); // 初始化控件

        // 注册广播接收器
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter("LinkData"));
    }

    /**
     * 自定义BroadcastReceiver
     * 用于接收广播
     */
    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            rgbIP = intent.getStringExtra("rgbIP");
            rgbPort = intent.getIntExtra("rgbPort", 0);
            rgbAddress = intent.getIntExtra("rgbAddress", 254);
            RTULink = intent.getBooleanExtra("RTULink", false);
            redChannelId = intent.getIntExtra("redChannelId", 1);
            greenChannelId = intent.getIntExtra("greenChannelId", 2);
            blueChannelId = intent.getIntExtra("blueChannelId", 3);
        }
    };

    /**
     * 初始化控件
     */
    void bind() {
        handler = new Handler(Looper.getMainLooper());

        lampBack = findViewById(R.id.lampBack);
        redSeekBar = findViewById(R.id.redSeekBar);
        greenSeekBar = findViewById(R.id.greenSeekBar);
        blueSeekBar = findViewById(R.id.blueSeekBar);
        rgbValueText = findViewById(R.id.rgbValueText);
        switchBtn = findViewById(R.id.switchBtn);
        settingBtn = findViewById(R.id.settingBtn);

        gradientDrawable = (GradientDrawable) lampBack.getDrawable();

        lampBack.setEnabled(false);
        redSeekBar.setEnabled(false);
        greenSeekBar.setEnabled(false);
        blueSeekBar.setEnabled(false);

        switchBtn.setOnClickListener(this);
        settingBtn.setOnClickListener(this);

        setSeekBar(new SeekBar[]{redSeekBar, greenSeekBar, blueSeekBar});   // 设置SeekBar的事件处理
    }

    /**
     * 设置SeekBar的事件处理
     *
     * @param viewList SeekBar列表
     */
    private void setSeekBar(SeekBar[] viewList) {
        for (final SeekBar view : viewList) {
            view.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                // SeekBar滑动时
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (view.getId() == R.id.redSeekBar) {
                        red = progress;
                    } else if (view.getId() == R.id.greenSeekBar) {
                        green = progress;
                    } else if (view.getId() == R.id.blueSeekBar) {
                        blue = progress;
                    }
                    gradientDrawable.setColor(Color.rgb(red, green, blue)); // 改变灯泡背景颜色
                    rgbValueText.setText(String.format("(%d,%d,%d)", red, green, blue));    // 更新RGB数值显示
                }

                // 按下SeekBarBtn时
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                // 松开SeekBarBtn时
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // 因为默认控制RGB的通道顺序为LED3,LED2,LED1
                    // 这里做了根据设置中的RGB三色通道适配,以达到无论怎么接,只要设置正确,控制效果就正常
                    int[] channelVal = new int[4];
                    channelVal[redChannelId - 1] = red;
                    channelVal[greenChannelId - 1] = green;
                    channelVal[blueChannelId - 1] = blue;
                    // 控制RGB颜色
                    ControlRGB(channelVal[0], channelVal[1], channelVal[2]).start();
                }
            });
        }
    }

    /**
     * 请求各通道Value
     * 注意:该方法为魔改方法，竞赛库中未提供，需要配合FindRGB.java使用
     */
    public void SendRGBValue(ConnectorListener listener) throws Exception {
        synchronized (dataBus) {
            dataBus.addClaimer(new ConnectorProtocolClaimerListenerImpl(listener, dataBus));
            dataBus.sendProtocol(new FindRGB(rgbAddress));
            dataBus.wait(1000L);
        }
    }

    /**
     * 解析RGB各通道Value
     * 注意:该方法伟魔改方法,竞赛库中未提供,配合SendRGBValue方法使用
     *
     * @param bytes response数据  通过DataBus中的getReceiveData方法获取
     * @return 各通道Value [channel1，channel2，channel3，channel4]
     */
    int[] getRGBValue(byte[] bytes) {
        int[] data = new int[4];
        if (bytes != null && bytes.length != 0) {
            for (int i = 0; i < 4; i++) {
                data[i] = HexUtil.hexStr2Int(DataTools.formatByteArray(new byte[]{bytes[4 + 2 * i]}).replace(" ", ""));
            }
        }
        return data;
    }

    /**
     * 初始化基础控件数据
     * 开启后读取RGB控制器的各通道值,根据设置的RGB三色通道号以及查询到的各通道值来初始化SeekBar的初始值,灯泡背景颜色与RGB数值
     */
    private void InitRGBView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SendRGBValue(new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            int[] data = getRGBValue(dataBus.getReceiveData());
                            red = data[redChannelId - 1];
                            green = data[greenChannelId - 1];
                            blue = data[blueChannelId - 1];

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // 设置SeekBar初始值
                                    redSeekBar.setProgress(red);
                                    greenSeekBar.setProgress(green);
                                    blueSeekBar.setProgress(blue);

                                    gradientDrawable.setColor(Color.rgb(red, green, blue)); // 改变灯泡背景颜色
                                    rgbValueText.setText(String.format("(%d,%d,%d)", red, green, blue));    // 更新RGB数值
                                }
                            });
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


    /**
     * 控制多通道
     * 控制通道LED1,LED2,LED3
     *
     * @param channelVal_1 LED3 Value
     * @param channelVal_2 LED2 Value
     * @param channelVal_3 LED1 Value
     * @return 线程
     */
    Thread ControlRGB(int channelVal_1, int channelVal_2, int channelVal_3) {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    rgbLed.controlRGB(channelVal_3, channelVal_2, channelVal_1, rgbAddress, new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            Log.i("ControlRGB", "OK!");
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    Log.e("ControlRGB", e.toString());
                }
            }
        });
    }

    /**
     * 控制RGB单通道
     *
     * @param channelID 通道ID
     * @param value     通道值
     * @return 线程
     */
    Thread ControlOneChannel(int channelID, int value) {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    rgbLed.controlRGBOne(channelID, value, rgbAddress, new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            Log.i("ControlOneChannel", "OK!");
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    Log.e("ControlOneChannel", e.toString());
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        // 开关按钮
        if (v.getId() == R.id.switchBtn) {
            // 判断是否设置过参数
            if (rgbIP == null) {
                Toast.makeText(this, "请先设置参数", Toast.LENGTH_SHORT).show();
            }
            // 参数设置已完成,开始连接
            else {
                // 判断是否已连接
                if (rgbLed == null) {
                    // 判断是否为串口连接
                    if (RTULink) {
                        // 初始化DataBus
                        dataBus = DataBusFactory.newSerialDataBus(Integer.parseInt(rgbIP), rgbPort);
                        // 初始化连接器
                        rgbLed = new RGBLed(dataBus, new ConnectResultListener() {
                            @Override
                            public void onConnectResult(boolean b) {
                                if (b) {
                                    Log.i("RTU  Status", "RTU Link OK!");

                                    InitRGBView();  // 初始化基础控件数据

                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            switchBtn.setImageResource(R.drawable.btn_switch_on);
                                            lampBack.setEnabled(true);
                                            redSeekBar.setEnabled(true);
                                            greenSeekBar.setEnabled(true);
                                            blueSeekBar.setEnabled(true);
                                        }
                                    });

                                } else {
                                    Log.i("RTU Status", "RTU Link Error!");
                                }
                            }
                        });
                    }
                    // TCP连接
                    else {
                        dataBus = DataBusFactory.newSocketDataBus(rgbIP, rgbPort);
                        rgbLed = new RGBLed(dataBus, new ConnectResultListener() {
                            @Override
                            public void onConnectResult(boolean b) {
                                if (b) {
                                    Log.i("TCP  Status", "TCP Link OK!");

                                    InitRGBView();  // 初始化基础控件数据

                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            switchBtn.setImageResource(R.drawable.btn_switch_on);
                                            lampBack.setEnabled(true);
                                            redSeekBar.setEnabled(true);
                                            greenSeekBar.setEnabled(true);
                                            blueSeekBar.setEnabled(true);
                                        }
                                    });


                                } else {
                                    Log.i("TCP Status", "TCP Link Error!");
                                }
                            }
                        });
                    }
                }
                // 断开连接
                else {
                    lampBack.setEnabled(false);
                    redSeekBar.setEnabled(false);
                    greenSeekBar.setEnabled(false);
                    blueSeekBar.setEnabled(false);

                    switchBtn.setImageResource(R.drawable.btn_switch_off);
                    rgbLed.stopConnect();
                    rgbLed = null;
                    dataBus = null;
                }
            }
        }
        // 设置按钮
        else if (v.getId() == R.id.settingBtn) {
            startActivity(new Intent(this, SettingActivity.class)); // 打开设置
        }
    }

    // 重写Activity销毁回调 销毁后取消注册广播
    @Override
    protected void onDestroy() {
        // 取消注册广播
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }
}